<?php
class UserIdentity extends CBaseUserIdentity {
	const ERROR_EMAIL_INVALID = 3;
	
	protected $_uid;
	protected $_email;
	protected $_username;
	protected $_password;
	
	protected $_method = 'email';

	public function __construct($username, $password, $method = 'email') {
		if($method == 'email'){
			$this->_email = $username;
			$this->_method = 'email';
		}else{
			$this->_username = $username;
			$this->_method = 'username';
		}
		$this->_password = $password;
	}

	public function authenticate() {
		if($this->_method == 'email')//authenticate with email
			$user = CActiveRecord::model('Member')->findByAttributes(array( 'email' => $this->_email, 'emailStatus' => 1 ));
		else //authenticate with username
			$user = CActiveRecord::model('Member')->findByAttributes(array( 'username' => $this->_username ));
		
		if($user == null)
			$this->errorCode = $this->_method == 'email' ? self::ERROR_USERNAME_INVALID : self::ERROR_EMAIL_INVALID;
		elseif($user->password != $user->hashPassword($this->_password))
			$this->errorCode = self::ERROR_PASSWORD_INVALID;
		else{
			$this->_uid = $user->uid;
			$this->_username = $user->username;
			$this->errorCode = self::ERROR_NONE;
		}

		return $this->errorCode == self::ERROR_NONE;
	}

	public function getId() {
		return $this->_uid;
	}

	public function getName() {
		return $this->_username;
	}
}

?>